/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * adminApplet.java
 *
 * Created on 05/10/2011, 1:07:45 PM
 */
package csse3004.GD.PM.Applet;

import com.turningtech.poll.Poll;
import com.turningtech.poll.PollService;
import com.turningtech.poll.Response;
import com.turningtech.poll.ResponseListener;
import com.turningtech.receiver.Receiver;
import com.turningtech.receiver.ReceiverService;
import com.turningtech.receiver.ResponseCardLibrary;
import csse3004.GD.DA.PollMasterDA;
import csse3004.GD.Question;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author s4206222
 */
public class adminApplet extends javax.swing.JApplet {

    private Poll poll;
    private ResponseListModel responseListModel = new ResponseListModel();
    private ReceiverListModel receiverListModel = new ReceiverListModel();
    private ReceiverListCellRenderer receiverCellRenderer = new ReceiverListCellRenderer();
    //dataset for poll results graph
    private DefaultCategoryDataset dataset;
    private int responseCount = 0;
    private PollMasterDA service = new PollMasterDA();
    private int pollID;
    private Question question;
    protected final Log logger = LogFactory.getLog(getClass());

    /** Initializes the applet adminApplet */
    public void init() {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        ResponseCardLibrary.turnDebuggingOn();

        ResponseCardLibrary.initializeLicense(
                "University of Queensland",
                "24137BBFEEEA9C7F5D65B2432F10F960");
        final int pid = Integer.parseInt("1");//TODO set to be args
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {

                public void run() {
                    initComponents();
                    initAll(pid);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void initAll(int pid) {
        this.pollID = pid;
        this.question = service.getActiveQuestion(pollID);
        initReceivers();
        initModel();
        if (receiverList.getModel().getSize() > 0) {
            receiverList.setSelectedIndex(0);
        }
        startPollHandler("Essay");
    }

    private void startPollHandler(String type) {
        //this.responseChart.setDataset((dataset = createDataset()));
        this.responseListModel.clear();
        try {//System.out.println("evt paramString: " + evt.getActionCommand());
            //see if it's an invalid response poll that we're starting
            if (type.equals("InvalidResponse")) {
                String answerRange = "246809";
                poll = PollService.createCorrectPoll(type, answerRange);
            } else {
                poll = PollService.createPoll();
            }
            poll.addResponseListener(new BasicResponseListener());
            Poll.PollingMode pollingMode = (Poll.PollingMode.valueOf(type));
            poll.start(pollingMode);
        } catch (Exception e) {
            showError("Unable to start poll.", e);
        }
    }

    private void initReceivers() {
        try {
            receiverListModel.addAll(ReceiverService.findReceivers());
        } catch (Exception e) {
            showError("Could not initialize receivers.", e);
        }
        dataset = createDataset();
    }

    private void initModel() {
        //responseChart.setDataset(dataset);

        responseList.setModel(responseListModel);
        receiverList.setModel(receiverListModel);
        receiverList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }
                int selection = receiverList.getSelectedIndex();
                try {
                    Receiver receiver = receiverListModel.get(selection);
                    lblChannel.setText(Integer.toString(receiver.getChannel()));
                    lblDescription.setText(receiver.getDescription());
                    lblId.setText(receiver.getId());
                    lblId1.setText(receiver.getVersion());
                } catch (Exception ex) {
                    //ignore
                }

            }
        });
        receiverList.setCellRenderer(receiverCellRenderer);

    }

    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        receiverList = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblDescription = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblChannel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblId1 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        label1 = new java.awt.Label();
        label2 = new java.awt.Label();
        label3 = new java.awt.Label();
        label4 = new java.awt.Label();
        dayTxt = new javax.swing.JFormattedTextField();
        hourTxt = new javax.swing.JFormattedTextField();
        minTxt = new javax.swing.JFormattedTextField();
        previous = new javax.swing.JButton();
        next = new javax.swing.JButton();
        PollResults = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        responseList = new javax.swing.JList();
        resCount = new javax.swing.JLabel();
        jToggleButton1 = new javax.swing.JToggleButton();

        jPanel1.setName("jPanel1"); // NOI18N

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Receivers"));
        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setPreferredSize(new java.awt.Dimension(350, 50));

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        receiverList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        receiverList.setName("receiverList"); // NOI18N
        jScrollPane1.setViewportView(receiverList);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Receiver Info"));
        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setPreferredSize(new java.awt.Dimension(350, 132));

        jLabel1.setText("Description:");
        jLabel1.setName("jLabel1"); // NOI18N

        lblDescription.setText("N/A");
        lblDescription.setName("lblDescription"); // NOI18N

        jLabel3.setText("Channel:");
        jLabel3.setName("jLabel3"); // NOI18N

        lblChannel.setText("N/A");
        lblChannel.setName("lblChannel"); // NOI18N

        jLabel2.setText("Id:");
        jLabel2.setName("jLabel2"); // NOI18N

        lblId.setText("N/A");
        lblId.setName("lblId"); // NOI18N

        jLabel4.setForeground(new java.awt.Color(204, 0, 0));
        jLabel4.setText("Firmware:");
        jLabel4.setName("jLabel4"); // NOI18N

        lblId1.setText("N/A");
        lblId1.setName("lblId1"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblChannel, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
                    .addComponent(lblDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))
                .addGap(102, 102, 102)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblId1)
                    .addComponent(lblId))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblChannel, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblId)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblId1)))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Timeout questions and close them for web users"));
        jPanel6.setName("jPanel6"); // NOI18N
        jPanel6.setPreferredSize(new java.awt.Dimension(350, 75));

        label1.setAlignment(java.awt.Label.RIGHT);
        label1.setName("label1"); // NOI18N
        label1.setText("Days");

        label2.setAlignment(java.awt.Label.RIGHT);
        label2.setName("label2"); // NOI18N
        label2.setText("Hours");

        label3.setAlignment(java.awt.Label.RIGHT);
        label3.setName("label3"); // NOI18N
        label3.setText("Minutes");

        label4.setFont(new java.awt.Font("Dialog", 0, 10));
        label4.setName("label4"); // NOI18N
        label4.setText("Or leave as zeros to never timeout");

        dayTxt.setText("0");
        dayTxt.setName("dayTxt"); // NOI18N
        dayTxt.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dayTxtFocusLost(evt);
            }
        });

        hourTxt.setText("0");
        hourTxt.setName("hourTxt"); // NOI18N
        hourTxt.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                hourTxtFocusLost(evt);
            }
        });

        minTxt.setText("0");
        minTxt.setName("minTxt"); // NOI18N
        minTxt.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                minTxtFocusLost(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dayTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hourTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(minTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                        .addGap(15, 15, 15))
                    .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dayTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(hourTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addComponent(minTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        previous.setText("Previous");
        previous.setName("previous"); // NOI18N
        previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previoushandleButtons(evt);
            }
        });

        next.setText("Next");
        next.setName("next"); // NOI18N
        next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nexthandleButtons(evt);
            }
        });

        PollResults.setBorder(javax.swing.BorderFactory.createTitledBorder("Poll Results"));
        PollResults.setName("PollResults"); // NOI18N
        PollResults.setPreferredSize(new java.awt.Dimension(350, 184));

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        responseList.setName("responseList"); // NOI18N
        jScrollPane2.setViewportView(responseList);

        resCount.setText("Responses:0");
        resCount.setName("resCount"); // NOI18N

        javax.swing.GroupLayout PollResultsLayout = new javax.swing.GroupLayout(PollResults);
        PollResults.setLayout(PollResultsLayout);
        PollResultsLayout.setHorizontalGroup(
            PollResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PollResultsLayout.createSequentialGroup()
                .addGap(252, 252, 252)
                .addComponent(resCount, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
        );
        PollResultsLayout.setVerticalGroup(
            PollResultsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PollResultsLayout.createSequentialGroup()
                .addComponent(resCount)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE))
        );

        jToggleButton1.setText("Show Responses");
        jToggleButton1.setName("jToggleButton1"); // NOI18N
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(previous, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(next, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
                .addGap(78, 78, 78))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                    .addComponent(PollResults, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER, false)
                    .addComponent(next)
                    .addComponent(previous))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PollResults, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        PollResults.setVisible(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void dayTxtFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dayTxtFocusLost
        try {
            if (dayTxt.getText().isEmpty()) {
                dayTxt.setText("0");
            }
            int temp = Math.abs(Integer.parseInt(dayTxt.getText()));
            dayTxt.setText(String.valueOf(temp));
        } catch (Exception E) {
        }
}//GEN-LAST:event_dayTxtFocusLost

    private void hourTxtFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_hourTxtFocusLost
        try {
            if (hourTxt.getText().isEmpty()) {
                hourTxt.setText("0");
            }
            int temp = Math.abs(Integer.parseInt(hourTxt.getText()));
            hourTxt.setText(String.valueOf(temp));
        } catch (Exception E) {
        }
}//GEN-LAST:event_hourTxtFocusLost

    private void minTxtFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_minTxtFocusLost
        try {
            if (minTxt.getText().isEmpty()) {
                minTxt.setText("0");
            }
            int temp = Math.abs(Integer.parseInt(minTxt.getText()));
            minTxt.setText(String.valueOf(temp));
        } catch (Exception E) {
        }
}//GEN-LAST:event_minTxtFocusLost

    private void previoushandleButtons(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previoushandleButtons
//////        this.responseListModel.clear();
//////        int seconds = 0;
//////        if (!minTxt.getText().isEmpty()) {
//////            seconds += Integer.parseInt(minTxt.getText()) * 60;
//////        }
//////        if (!hourTxt.getText().isEmpty()) {
//////            seconds += Integer.parseInt(hourTxt.getText()) * 60 * 60;
//////        }
//////        if (!dayTxt.getText().isEmpty()) {
//////            seconds += Integer.parseInt(dayTxt.getText()) * 60 * 60 * 24;
//////        }
//////        if (evt.getActionCommand().equals(next.getActionCommand())) {
//////            //TODO David Confirmation message
//////            int nextID = service.setNext(true, pollID, seconds);
//////            if (nextID != -1) {
//////                question = service.getActiveQuestion(pollID);
//////                if (question.getId() != nextID) {
//////                    logger.info("Critical error in setNext or getActiveQuestion");
//////                } else {
//////                    logger.info("there was no next question");
//////                }
//////            }
//////        } else {
//////            int nextID = service.setNext(false, pollID, seconds);
//////            if (nextID != -1) {
//////                question = service.getActiveQuestion(pollID);
//////                if (question.getId() != nextID) {
//////                    logger.info("Critical error in setNext or getActiveQuestion");
//////                } else {
//////                    logger.info("there was no next question");
//////                }
//////            }
//////        }
}//GEN-LAST:event_previoushandleButtons

    private void nexthandleButtons(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nexthandleButtons
//        this.responseListModel.clear();
//        int seconds = 0;
//        if (!minTxt.getText().isEmpty()) {
//            seconds += Integer.parseInt(minTxt.getText()) * 60;
//        }
//        if (!hourTxt.getText().isEmpty()) {
//            seconds += Integer.parseInt(hourTxt.getText()) * 60 * 60;
//        }
//        if (!dayTxt.getText().isEmpty()) {
//            seconds += Integer.parseInt(dayTxt.getText()) * 60 * 60 * 24;
//        }
//        if (evt.getActionCommand().equals(next.getActionCommand())) {
//            //TODO David Confirmation message
//            int nextID = service.setNext(true, pollID, seconds);
//            if (nextID != -1) {
//                question = service.getActiveQuestion(pollID);
//                if (question.getId() != nextID) {
//                    logger.info("Critical error in setNext or getActiveQuestion");
//                } else {
//                    logger.info("there was no next question");
//                }
//            }
//        } else {
//            int nextID = service.setNext(false, pollID, seconds);
//            if (nextID != -1) {
//                question = service.getActiveQuestion(pollID);
//                if (question.getId() != nextID) {
//                    logger.info("Critical error in setNext or getActiveQuestion");
//                } else {
//                    logger.info("there was no next question");
//                }
//            }
//        }
}//GEN-LAST:event_nexthandleButtons

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        PollResults.setVisible(!PollResults.isVisible());
        //TODO make window grow when clicked
}//GEN-LAST:event_jToggleButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PollResults;
    private javax.swing.JFormattedTextField dayTxt;
    private javax.swing.JFormattedTextField hourTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToggleButton jToggleButton1;
    private java.awt.Label label1;
    private java.awt.Label label2;
    private java.awt.Label label3;
    private java.awt.Label label4;
    private javax.swing.JLabel lblChannel;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblId1;
    private javax.swing.JFormattedTextField minTxt;
    private javax.swing.JButton next;
    private javax.swing.JButton previous;
    private javax.swing.JList receiverList;
    private javax.swing.JLabel resCount;
    private javax.swing.JList responseList;
    // End of variables declaration//GEN-END:variables

    private void initPoll(String evt) {

        //this.responseChart.setDataset((dataset = createDataset()));
        try {
            poll = PollService.createPoll();
            poll.addResponseListener(new BasicResponseListener());
            Poll.PollingMode pollingMode = (Poll.PollingMode.valueOf(evt));
            poll.start(pollingMode);
            //responseChart.setSubtitle(evt + " Polling Open");
        } catch (Exception e) {
            showError("Unable to start poll.", e);
        }
    }

    private void showError(String message, Exception e) {
        JOptionPane.showMessageDialog(null, message + "\n Reason:" + e.getMessage());
    }

    private DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset newDataset = new DefaultCategoryDataset();
        List<Receiver> receivers = receiverListModel.getReceivers();
        for (Receiver receiver : receivers) {
            for (int i = 0; i < 10; i++) {
                newDataset.addValue(0, receiver.getId(), Integer.toString(i));
            }
        }

        return newDataset;

    }

    private class ReceiverListModel extends DefaultListModel {

        private List<Receiver> receivers = new ArrayList();

        @Override
        public void clear() {
            receivers.clear();
            fireContentsChanged(this, 0, 0);
        }

        public void addAll(Collection newData) {

            receivers.addAll(newData);
            fireContentsChanged(this, 0, 0);
        }

        @Override
        public int getSize() {
            return receivers.size();
        }

        @Override
        public Object getElementAt(int index) {
            return receivers.get(index);
        }

        @Override
        public Receiver get(int index) {
            return receivers.get(index);
        }

        public List<Receiver> getReceivers() {
            return receivers;
        }
    }

    private class ReceiverListCellRenderer extends JLabel implements ListCellRenderer {

        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {

            Receiver r = receiverListModel.get(index);

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setOpaque(true);
            setText(r.getId());

            return this;
        }
    }

    private class ResponseListModel extends DefaultListModel {

        List<Response> responses = new ArrayList();

        @Override
        public void clear() {
            responses.clear();
            responseCount = 0;
            fireContentsChanged(this, 0, 0);
        }

        public void add(Response newData) {
            logger.info("response:"+ newData.getResponse());
            
            if (service.addResponse(newData.getResponseCardId(), newData.getResponse(), question.getId()) == 2) {
                responseCount++;
                resCount.setText("Resoponses:" + responseCount++);
            }
            responses.add(newData);
            fireContentsChanged(this, getSize() - 2, getSize() - 1);
        }

        @Override
        public int getSize() {
            return responses.size();
        }

        @Override
        public Object getElementAt(int index) {
            return responses.get(index);
        }
    }

    private class BasicResponseListener implements ResponseListener {

        public BasicResponseListener() {
        }

        public void responseReceived(Response response) {
            responseListModel.add(response);
            if (response.getReceiverId() == null
                    || response.getResponse() == null
                    || response.getResponse().equals("?")) {
                return;
            }

//            if (!dataset.getColumnKeys().contains(response.getResponse()))

            /**
            Number count = dataset.getValue(response.getReceiverId(), response.getResponse());
            if (count == null) {
            count = new Integer(1);
            }
             */
            //dataset.incrementValue(1, response.getReceiverId(), response.getResponse());
        }
    }

    private class SetChannelAction extends AbstractAction {

        public SetChannelAction() {
            putValue(Action.NAME, "Set Channel");
            putValue(Action.LONG_DESCRIPTION, "Set Channel");
        }

        public void actionPerformed(ActionEvent arg0) {
            try {

                int index =
                        receiverList.getSelectionModel().getAnchorSelectionIndex();
                if (index < 0) {
                    return;
                }
                List<Receiver> receivers = receiverListModel.getReceivers();
                Receiver r = receivers.get(index);
                String channel = JOptionPane.showInputDialog("Please enter the new channel:");
                if (channel == null) {
                    return;
                }
                r.setChannel(Integer.parseInt(channel));
                lblChannel.setText(Integer.toString(r.getChannel()));

            } catch (Exception ex) {
                Logger.getLogger(PollingDemoPresentMode.class.getName()).log(
                        Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Could not set the channel.");
            }
        }
    }
}
